﻿@{
 ViewBag.Title = "Creating a ASP MVC CRUD application";
 Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Creating a ASP MVC CRUD application</h2>
<h3>Adding validation to create applicants view</h3>
<p>If you read the tutorial <a href="/ASPMVCForm" target="_blank">Creating a ASP.NET MVC Contact Form</a>, then you’re familiar with validation in  MVC. </p>
<p>If you haven’t, let’s analyze it in our create applicants view.</p>
<p>If a user leaves all fields empty, and left clicks create,  MVC through various layers of abstraction translates the validity of the model state from the controller, which uses various data requirements within the model to determine what rules have passed or failed. </p>
<p>In  ASP web forms we added validation messages and requirements within a web form using out of the box validation controls whereas in MVC we add validation messages and requirements in our model class.  Follow these steps to add validation:</p>
<ul class="indent">
<li>From solution explorer, expand our Models class</li>
<li>Double click Applicant.cs</li>
</ul>
<pre class="brush:csharp">
public class Applicants
{
[Key]
public int ApplicantId { get; set;}
[Required(ErrorMessage="First name is required")]
public string FirstName { get; set; }
[Required(ErrorMessage="Last name is required")]
public string LastName { get; set; }
[Required(ErrorMessage="City is required")]
public string City { get; set; }
[Required(ErrorMessage="State is required")]
public string State { get; set; }
[Required(ErrorMessage="Zip Code is required")]
public string ZipCode { get; set; }
}
</pre>
<p>As you can see from the code:</p>
<ul class="indent">
<li>We add a data annotation above each public property in our model class with the necessary parameters passed in</li>
</ul>
<p>If you’re familiar with validation controls in  ASP web forms data annotations in  MVC are a new and improved way of handling validation at the business/entity layer of an application and translating that back through associated bindings in the corresponding view. Data annotations in  MVC have similar attributes that were applicable in  ASP  web forms. The idea in MVC is to delegate the responsibilities of behavior through layers of abstraction between the views, models, data access layer and controllers so that we don’t have an application that has a mixture of these behaviors where they don’t belong.</p>
<p>Save your changes and when left clicking create from the create applicant view without entering a few input fields you’ll receive the following screen:</p>
<p align="center"><a href="@Url.Content("~/content/aspmvccrud/images/validation_showing.jpg")" data-lightbox="Validation Showing"><img src="@Url.Content("~/content/aspmvccrud/images/thumbs/validation_showing.jpg")" alt="Add Scaffold" width="300" height="190" /></a></p>
<p>If you view the source of the razor page before and after validation occurs, you’ll notice MVC injects the appropriate attributes into the HTML markup to display validation messages. This is one more way MVC handles obtrusive JavaScript from being unnecessarily injected into a web page.</p>
<h3>Viewing edit, details and delete views</h3>
<p>From our applicant home page, we have links in the grid that navigates to an edit view, which takes care of performing edit operations against existing applicants, details view is a view which allows us to view a read-only version of each applicant, while the delete view is a bit more complex, which will be covered shortly. </p>
<p>Each applicant in the grid is prefaced with a unique number generated by  MVC and from a query performed by entity framework:</p>
<pre class="brush:csharp">
// GET: /Applicant/
public ActionResult Index()
{
return View(db.Applicant.ToList());
}
</pre>
<p>As you can see from the code:</p>
<ul class="indent">
<li>We have a method named Index with an implicit GET command which returns a collection of applicants using the ToList method from entity framework</li>
</ul>
<p>The link(s) for each applicant are generated by:</p>
<pre class="brush:html">
foreach (var item in Model) {
&lt;tr&gt;
&lt;td&gt;
Html.DisplayFor(modelItem => item.FirstName)
&lt;/td&gt;
&lt;td&gt;
Html.DisplayFor(modelItem => item.LastName)
&lt;/td&gt;
&lt;td&gt;
Html.DisplayFor(modelItem => item.City)
&lt;/td&gt;
&lt;td&gt;
Html.DisplayFor(modelItem => item.State)
&lt;/td&gt;
&lt;td>
Html.DisplayFor(modelItem => item.ZipCode)
&lt;/td&gt;
&lt;td>
Html.ActionLink("Edit", "Edit", new { id=item.ApplicantId }) |
Html.ActionLink("Details", "Details", new { id=item.ApplicantId }) |
Html.ActionLink("Delete", "Delete", new { id=item.ApplicantId })
&lt;/td&gt;
&lt;/tr&gt;
}
</pre>
<p>Note: You will need to preface the following with (at) symbol: foreach and Html</p>
<p>As you can see from the code:</p>
<ul class="indent">
<li>We use a for each loop to iterate through the applicant collection and display information</li>
<li>We use an HTML object, and call the class method action link, and pass in an appropriate action behaviors while setting a new applicant id for each</li>
</ul>
<p>When using action links,  MVC uses a default configuration to determine how to create the link with parameters as well as how to route the request within an application. Configuring routing can be a complex topic. If you need to create links with different parameters you want to view RouteConfig.cs. From solution explorer navigate to:</p>
<ul class="indent">
<li>
App_Start
<ul>
<li>RouteConfig.cs</li>
</ul>
</li>
</ul>
<p>With regards to deleting applicants we have two delete views. The link from the applicant home page is similar to view detail functionality. We send a user to a confirmation page asking them if this is the correct record to delete. The code used for this is:</p>
<pre class="brush:csharp">
// GET: /Applicant/Delete/5
public ActionResult Delete(int? id)
{
         
Applicants applicants = db.Applicant.Find(id);
            
return View(applicants);
}
</pre>
<p>As you can see from the code:</p>
<ul class="indent">
<li>We have an implicit GET command named Delete</li>
<li>We’re expecting a id from the address bar, if found:
<ul>
<li>We create an object from our applicants model named applicants and call the Find method from our data context class:</li>
<li>As long as the id exists in the database, we’ll return the specific user requested back to our view</li>
</ul>
</li>
</ul>
<p>When the user presses delete from this web page, we have another method which executes the desired action against the database:</p>
<pre class="brush:csharp">
// POST: /Applicant/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
Applicants applicants = db.Applicant.Find(id);
db.Applicant.Remove(applicants);
db.SaveChanges();
return RedirectToAction("Index");
}
</pre>
<p> As you can see from the code:</p>
<ul class="indent">
<li>We have an explicit POST command named Delete</li>
<li>We’re expecting a id from the address bar, if found:
<ul>
<li>We create an object from our applicants model named applicants and call the Find method from our data context class:</li>
<li>As long as the id exists in the database, we’ll remove the desired applicant from the database </li>
<li>We’ll call SaveChanges to perform the operation against the database via entity framework</li>
<li>Redirect our user to the home page</li>
</ul>
</li>
</ul>
<h3>A few caveats</h3>
<p>The application as it stands uses  MVC’s native routing structure to define how uniform resource locators (URL’s) are created. In other words, our URL’s look as below:</p>
<p>http://localhost:&lt;port_number&gt;/Applicant/Edit/2</p>
<p>Depending on the uses of this application, this may/may be desired to pass an easily identifiable indexer as part of the URL string. If this is the case, you’ll want to look into passing a global unique identifier (GUID) instead</p>
<p>Also, as the application stands, anyone can add, update, remove applicant records from this system. Depending on the uses of this application, that may/may not be the desired approach.</p>
<h3>Summary</h3>
<p>In this tutorial we learned how to create a simple create, read, update and delete (CRUD) application using Visual Studio, MS SQL Server, MVC and Entity Framework. Specifically we learned:</p>
<ul class="indent">
<li>How to create the solution in Visual Studio</li>
<li>How to create the database, and table in MS SQL Server Management Studio</li>
<li>Approaches to creating entity framework within MVC</li>
<li>Creation of our model, data context and controller classes and associated keys in web.config</li>
<li>Understanding the differences between traditional  ASP web forms and ASP MVC</li>
<li>Understanding how validation works in MVC</li>
<li>Creation, editing, viewing and deleting applicant records using our Razor web pages</li>
</ul>
<p>With the information learned in this tutorial, you can create, customize and put a small - medium - large scale administrative system in place rather easily and quickly with ASP MVC.</p>
<p>If you have questions, @Html.ActionLink("contact me", "Contact", "Home")</p>